# -*- coding:utf-8 -*-
import uuid

from captcha.conf.settings import settings
import logging

from django.core.files.uploadedfile import InMemoryUploadedFile
from rest_framework.exceptions import APIException

from django.http import FileResponse

logger = logging.getLogger("django")


# 上传图片文件
def file_save(request, fileFolder):
    import os
    obj: InMemoryUploadedFile = request.FILES.get('file', None)
    logger.info(obj.__class__.__name__)
    # logger.info(request.FILES)
    # logger.info(obj.__dir__())
    logger.info(obj.name)  # qrsbbjrvr1hqrsbbjrvr1h.jpg
    logger.info(obj.content_type)  # image/jpeg
    logger.info(obj.content_type_extra)  # {}
    logger.info(obj.size)  # 786282  单位字节 1KB等于1024字节，1MB等于1024KB，1GB等于1024MB，1TB等于1024GB
    logger.info(obj.field_name)  # file
    # logger.info(obj.encoding)
    logger.info(obj.charset)  # None
    logger.info(obj.fileno)
    """
    ['file', '_name', 'size', 'content_type', 'charset', 'content_type_extra', 'field_name', '__module__', '__doc__',
     '__init__', 'open', 'chunks', 'multiple_chunks', '__repr__', '_get_name', '_set_name', 'name',
     'DEFAULT_CHUNK_SIZE', '__str__', '__bool__', '__len__', '__iter__', '__enter__', '__exit__', 'close', 'encoding',
     'fileno', 'flush', 'isatty', 'newlines', 'read', 'readinto', 'readline', 'readlines', 'seek', 'tell', 'truncate',
     'write', 'writelines', 'closed', 'readable', 'writable', 'seekable', '__dict__', '__weakref__', '__hash__',
     '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__',
     '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__',
     '__dir__', '__class__']
    """

    # 创建文件夹
    if not os.path.exists(os.path.join(settings.BASE_DIR, "static", fileFolder)):
        os.makedirs(os.path.join(settings.BASE_DIR, "static", fileFolder))

    # obj.name 原始文件名
    fileName = str(uuid.uuid4())
    try:
        fileName = fileName.replace("-", "a") + "." + obj.name.split('.')[-1]
    except Exception as e:
        raise APIException("文件上传异常")
    path = "/" + "static" + "/" + fileFolder + "/" + fileName
    file_path = os.path.join(settings.BASE_DIR, "static", fileFolder, fileName)
    with open(file_path, 'wb') as f:
        for chunk in obj.chunks():
            f.write(chunk)
    return path


# 下载文件
def fileDownload(path):
    file = open(path, 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="PayTemplate.jpg"'
    # PayTemplate.jpg 返回文件的名称
    return response


# 上传任意文件
def postFileSave(request, fileFolder):
    """

    :param request:
    :param fileFolder: 文件夹名
    :return:
    """
    import os
    obj = request.FILES.get('file', None)
    logger.info(request.FILES)

    if not os.path.exists(os.path.join(settings.BASE_DIR, "static", fileFolder)):
        os.makedirs(os.path.join(settings.BASE_DIR, "static", fileFolder))

    path = "static" + "/" + fileFolder + "/" + obj.name

    filePath = os.path.join(settings.BASE_DIR, 'static', fileFolder, obj.name)
    with open(filePath, 'wb') as f:
        for chunk in obj.chunks():
            f.write(chunk)

    return path
